package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealMapper setmealMapper;
    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     * @param setmealDto
     */
    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);

        Long setmealId = setmealDto.getId();

        //保存套餐菜品数据到setmeal_dish表
        List<SetmealDish> dishs = setmealDto.getSetmealDishes();
//        dishs.stream().map((item) -> {
//            item.setSetmealId(setmealDto.getId());
//            return item;
//        }).collect(Collectors.toList());

        for (SetmealDish dish : dishs) {
            dish.setSetmealId(setmealId);
        }

        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(dishs);
    }
    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public R<Page> findByPage(int page, int pageSize, String name) {
        Page<SetmealDto> pageInfo = new Page<>(page,pageSize);
        //调用mapper接口方法利用sql语句实现多表查询
        List<SetmealDto> setmealDtoList = setmealMapper.findByPage(pageInfo, name);
        //将返回结果集存入pageInfo
        pageInfo.setRecords(setmealDtoList);
        return R.success(pageInfo);
    }
    /**
     * 批量删除套餐
     * @param ids
     */
    @Transactional
    @Override
    public void deleteByIds(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(ids != null, Setmeal::getId, ids);
        List<Setmeal> setmealList = this.list(lqw);

        if (setmealList!=null){
            for (Setmeal setmeal : setmealList) {
                //要先判断该套餐是否为停售状态，否则无法删除并且抛出异常
                if (setmeal.getStatus()==0) {
                    this.removeByIds(ids);
                }else {
                    throw new CustomException("有套餐正在售卖，无法全部删除！");
                }
            }
        }
    }
    /**
     * 状态修改
     * @param status
     * @param ids
     * @return
     */
    @Override
    public R<String> setStatus(Integer status, List<Long> ids) {
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(ids != null, Setmeal::getId, ids);
        List<Setmeal> list = this.list(lqw);
        if (list!=null) {
            for (Setmeal setmeal : list) {
                setmeal.setStatus(status);
                this.updateById(setmeal);
            }
        }
        return R.success("状态修改成功");
    }
    /**
     * 查询状态为1（起售状态）的套餐
     * @param setmeal
     * @return
     */
    @Override
    public R<List<Setmeal>> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId, setmeal.getCategoryId());

        //添加条件，查询状态为1（起售状态）的套餐
        lqw.eq(Setmeal::getStatus,setmeal.getStatus());
        //添加排序条件
        lqw.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmealList = this.list(lqw);
        return R.success(setmealList);
    }
    /**
     * 根据id查询套餐信息和对应的菜品信息
     * @param id
     * @return
     */
    @Override
    public SetmealDto getByIdWithDish(Long id) {
//        A. 根据ID查询套餐的基本信息
        Setmeal setmeal = this.getById(id);
//        B. 根据套餐的ID查询套餐菜品列表数据
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);
//        C. 组装数据并返回
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,setmeal.getId());
        List<SetmealDish> dishes = setmealDishService.list(lqw);
        setmealDto.setSetmealDishes(dishes);
        return setmealDto;
    }
    /**
     * //更新setmeal表基本信息
     * @param setmealDto
     */
    @Transactional
    @Override
    public void updateWithDish(SetmealDto setmealDto) {
        //更新setmeal表基本信息
        this.updateById(setmealDto);

        //清理当前套餐对应菜品数据---setmeal_dish表的delete操作
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper();
        lqw.eq(SetmealDish::getSetmealId, setmealDto.getId());

        setmealDishService.remove(lqw);
        //添加当前提交过来的菜品数据---setmeal_dish表的insert操作
        List<SetmealDish> dishes = setmealDto.getSetmealDishes();
        dishes = dishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(dishes);
    }


}
